#include "StdAfx.h"
#include "SCDev.h"

volatile int SCDev::m_Refcnt = 0;
SerialPort SCDev::Dev;
CMutex SCDev::mutex;
time_t SCDev::RspTime = 0;

SCDev::SCDev(void)
{
}

SCDev::~SCDev(void)
{
}

bool SCDev::open(const wchar_t *portName, int baudRate)
{
	bool ret = true;
    
	lock();

    m_Refcnt ++;

	if (m_Refcnt == 1)
	{
        ret = Dev.open(portName, baudRate);
	}
    
	unlock();

	return ret;
}

bool SCDev::close()
{
	lock();

	if (m_Refcnt == 1)
	{
        Dev.close();
	}

    if (m_Refcnt > 0)
	{
        m_Refcnt --;
	}

	unlock();

	return true;
}

int SCDev::write(unsigned char *buf, int size)
{
    return Dev.write(buf, size);
}

int SCDev::read(unsigned char *buf, int size)
{
	int len;

	len = Dev.read(buf, size);
    if (len > 0)
	{
        RspTime = time(NULL);
	}

	return len;
}

void SCDev::lock()
{
    mutex.Lock();
}

void SCDev::unlock()
{
    mutex.Unlock();
}

void SCDev::clearbuf()
{
    Dev.clearbuf();
}

time_t SCDev::rsptime()
{
    return RspTime;
}

void SCDev::setretry(int cnt)
{
    Dev.setretry(cnt);
}
